{* $Id$ *}
{include_core file="admin/lib/header.html" title="退货列表"}
<style>
  .goods-info{
    display:block;
    float:left;
    margin-left:5px;
    line-height:20px;
    width:65%;
  }
  .goods-info p{
    margin-top: 5px;
    height:16px;
    line-height: 16px;
    padding-left: 5px;
    padding-right: 5px;
    brefund:1px solid #EDEDED;
    background:#EFEFEF;
    display:inline-block;
  }
  .goods-table td{
    brefund:1px solid #EDEDED;
  }
  .goods-info a:first-child{
    color:#333;
  }
  .goods-info a:nth-child(2){
    color:#05A;
  }
  .goods-info a:hover{
    color:#23a18b;
  }
  .js_refundTable td{
    padding-top:10px;
    padding-bottom:10px;
  }
</style>
{$refund_status_list = refund_config::$refund_status_list}
  <div class="page-header border-bottom clearfix">
    <h2 class="left">退货管理<span>在这里对退货进行管理</span></h2>
    <a style="margin-top:5px; display:block; float:right;" href="{AnUrl('refund/admin/download_list')}?search_filter[refund_id]={$search_filter.refund_id}&search_filter[order_id]={$search_filter.order_id}&search_filter[user_name]={$search_filter.user_name}&search_filter[refund_status]={$search_filter.refund_status}&refund_status={$refund_status}" class="btn btn-xs btn-primary js_downList">导出EXCEL</a>
  </div>
  <div class="search-level1 clearfix" style="display:none">
    <form action="refund/admin" method="get">
      <input type="hidden" name="is_advenced" value="0">
      <input type="hidden" name="status" value="{$status}">
      <input {if $is_advenced == 1}style="display:none;"{/if} type="text" class="left" name="search_filter[refund_code]" value="{$search_filter.refund_code}" placeholder="输入退货号搜索">
      <button {if $is_advenced == 1}style="display:none;"{/if} type="submit" class="btn btn-success btn-sm left">搜索</button>
      {*<a href="javascript:void(0);" class="close js_advanced {if $is_advenced == 1}js_isOpen open{/if}">高级搜索<em></em></a>*}
    </form>
  </div>
  <div class="search-form js_advancedForm" {if $is_advenced == 0}style="display:none;"{/if}>
    <form action="refund/admin" method="get" class="js_refundSearchForm">
      <input type="hidden" name="is_advenced" value="1">
      <input type="hidden" name="status" value="{$status}">
      <p>
        <label for="" class="search-f-label">退货单号：</label>
        <input type="text" class="search-f-ipt1" name="search_filter[refund_id]" value="{$search_filter.refund_id}">
      </p>
      <p>
        <label for="" class="search-f-label">订单号：</label>
        <input type="text" class="search-f-ipt1" name="search_filter[order_id]" value="{$search_filter.order_id}">
      </p>
      <p>
        <label for="" class="search-f-label">商品标题：</label>
        <input type="text" class="search-f-ipt1" name="search_filter[goods_title]" value="{$search_filter.goods_title}">
      </p>
      <p>
        <label for="" class="search-f-label">用户名称：</label>
        <input type="text" class="search-f-ipt1" name="search_filter[user_name]" value="{$search_filter.user_name}">
      </p>
      <p>
        <label for="" class="search-f-label">退货状态：</label>
        <select class="search-f-slt1" name="search_filter[refund_status]">
          <option value="">全部</option>
          {foreach $refund_status_list as $k=>$v}
            <option value="{$k}" {if $search_filter.refund_status == $k}selected{/if}>{$v}</option>
          {/foreach}
        </select>
      </p>
      <p>
      <label for="" class="search-f-label">添加时间：</label>
        <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[start_date]" value="{$search_filter.start_date}" id="startDate">
        <span class="search-f-line"></span>
        <input type="text" class="search-f-ipt1 search-f-ipt2" name="search_filter[end_date]" value="{$search_filter.end_date}" id="stopDate">
      </p>
      <p><label for="" class="search-f-label"></label><button type="submit" class="btn btn-success btn-xs js_searchBtn">搜索</button></p>
    </form>
  </div>
  <!--start:列表-->
  <table class="list-table goods-table">
    <caption>按状态：
      <a href='{AnUrl("refund/admin")}' {if !$refund_status && $status != '' && !$search_filter.refund_status} class="label label-primary" {else} class="label label-default" {/if}>全部</a>
      {foreach $refund_status_list as $k=>$v}
        <a href='{AnUrl("refund/admin?refund_status=$k")}' {if $refund_status == $k || $search_filter.refund_status == $k} class="label label-primary" {else} class="label label-default" {/if}>{$v}</a>
      {/foreach}
    </caption>
    <thead>
      <tr>
        {if $status == 1}
        <th style="width:20px;"><input type="checkbox" class="selectAll"></th>
        {/if}
        <th style="min-width:150px">退货单号</th>
        <th>退货状态</th>
        <th style="min-width:160px">订单信息</th>
        <th>退款总金额</th>
        <th>商家备注</th>
        <th>详细信息</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      {foreach $refund_list as $k=>$v}
        <tr data-id="{$v.id}" data-type="{$v.pay_type}">
          {if $status == 1}
          <td><input type="checkbox" class="listSelect"></td>
          {/if}
          <td>
            NBD编码：{order_helper::order_id_encode($v.id, 2)}<br />
            ERP编码: {$v.erp_refund_id}<br />
            {*
            {if $v.transaction_id}
            支付宝退款交易号:<br />{$v.transaction_id}<br />
            {/if}
            *}
            下单用户: {user_helper::get_nick_name($v.user_id)}
          </td>
          <td><span class="label {if $v.refund_status == 1}label-warning{elseif $v.refund_status == 5}label-primary{elseif $v.refund_status == 10}label-success{elseif $v.refund_status == 15}label-info{elseif $v.refund_status == 20}label-default{else}label-default{/if}">{$refund_status_list.{$v.refund_status}}</span></td>
          {$order_info = _uri('order', $v.order_id)}
          {$origin = $order_info.origin}
          <td>
            NBD编码: {order_helper::order_id_encode($v.order_id)}<br />
            ERP编码: {$order_info.erp_order_id}<br />
            {if $order_info.transaction_id}
            {openapi_config::$pay_type[$order_info.pay_type]['title']}交易号:<br />{$order_info.transaction_id}<br />
            {/if}
            订单来源: {if $origin == 'm'}手机端{else}PC端{/if}<br />
            {$order_status = order_helper::get_order_status($v.order_id)}
            订单状态: {order_config::$dealer_progress.$order_status}
          </td>
          <td class="js_refundTotalPrice_{$v.id}">
            {if $v.is_modify_price}{$v.real_price}{else}{$v.refund_price}{/if}
          </td>
          <td>{$v.note}</td>
          <td>
            <span class="btn btn-xs btn-primary refund_info">详细信息</span>
            <span class="btn btn-xs btn-primary js_showLogBtn" data-res_name="refund" data-res_id="{$v.id}">订单log</span>
          </td>
          <td>
            {if $v.refund_status == 1}
              {if $order_status == 20}
                <span class="btn btn-xs btn-primary js_refundPayPrice" data-type="agree">申请通过</span>
                <span class="btn btn-xs btn-danger refundCancel">申请驳回</span>
              {/if}
            {elseif $v.refund_status == 15}
              {if $v.refund_pay_status >= 1}
              <span class="btn btn-xs btn-success js_refundPayPrice" data-type="refund">重新提交退款</span>
              {else}
              <span class="btn btn-xs btn-success js_refundPayPrice" data-type="refund">退款</span>
              {/if}
            {elseif $v.refund_status > 1 && $v.refund_status < 15}
              <span class="btn btn-xs btn-success js_refundPayPrice" data-type="refund">退款</span>
            {/if}
            {if ($v.refund_status == 15 || $v.refund_status == 5) && !$v.user_express && !$v.refund_express}
              <span class="btn btn-xs btn-danger cancelRefund">取消退货</span>
            {/if}
            {if $v.refund_status == 23}
              <span class="btn btn-xs btn-danger js_compRefundBtn">完成退款</span>
            {/if}
          </td>
        </tr>
      {foreachelse}
        <tr><td class="txtleft" colspan="10">暂无数据</td></tr>
      {/foreach}
    </tbody>
    {if $status == 1}
    <tfoot>
      <tr>
        <td><input type="checkbox" class="selectAll"></td><td colspan="9">
        {*<a href="{AnUrl("refund/admin/ajax_process_list")}" class="btn btn-danger btn-xs js_processRefund">批量退款</a>*}
        </td>
      </tr>
    </tfoot>
    {/if}
  </table>
  <!-- 遮罩 -->
  <div class="float-bg" style="z-index: 19999; display: none"></div>
  {include_core file="admin/lib/pager.html"}
<!--end:列表-->
{load_js file='zclip/jquery.zclip.min.js'}
{load_js file='zclip/ZeroClipboard.js'}
<script>
var resName = 'refund';
var jsrefundId = "{$search_filter.refund_id}";
$('.js_refundId').load(siteUrl+'/refund/load_refund_option?res_name='+resName,function(){
  $('.js_refundId').find('option').each(function(){
    if ($(this).attr('value') == jsrefundId) {
      $(this).attr('selected','selected');
    }
  });
});
$(function(){
  // 高级搜索
  $('.js_advanced').click(function(e){
    e.preventDefault();
    var thisObj = $(this);
    var outBox  = thisObj.closest('form');
    if (thisObj.hasClass('js_isOpen')) {
      thisObj.removeClass('js_isOpen open');
      outBox.find('input').show();
      outBox.find('button').show();
      $('.js_advancedForm').hide();
    } else {
      thisObj.addClass('js_isOpen open');
      outBox.find('input').hide();
      outBox.find('button').hide();
      $('.js_advancedForm').show();
    }
  });
  
  // 高级搜索时间验证
  $('.js_searchBtn').click(function(e){
    e.preventDefault();
    var thisObj   = $(this);
    var startDate = $.trim($('#startDate').val());
    var stopDate  = $.trim($('#stopDate').val());
    if (startDate > stopDate) {
      showMsg('结束时间应大于等于开始时间');
      return;
    }
    thisObj.closest('form').submit();
  });

  // 页面复制
  var clip = new ZeroClipboard( $('.js_copyList'), {
    moviePath: "../../../../js/zclip/ZeroClipboard.swf"
  });
  clip.on( 'complete', function(client, args) {
    showMsg("复制成功，复制内容为："+ args.text, 1);
  });
  
  // 退款失败完成退款
  $('.js_compRefundBtn').click(function(){
    var id = $(this).closest('tr').data('id');
    var thisBtn = $(this);
    $.post(
        "{AnUrl("refund/admin/ajax_refund_info")}",
        { id:id },
        function(data){
          var d = ace.dialog({
            'title':'手动完成退款确认',
            'content':data,
            'width':1000,
            'cancel':function(){
              d.close();
            },
            'okValue': '确认完成退款',
            'ok': function(){
              $.post("{AnUrl('refund/admin/refund_complete_by_user')}", { id:id }, function(json){
                if(json.info == 'ok') {
                  alert('更新成功！');
                  d.close();
                  thisBtn.closest('tr').fadeOut(function(){
                    $(this).remove();
                  });
                } else {
                  alert(json.info);
                }
              }, 'json').error(function(){
                alert("网络错误，请刷新重试");
              });
            }
          })
        }
    )
  });
  
  // 显示退货的详细信息
  $('.refund_info').click(function(){
    var id = $(this).closest('tr').data('id');
    $.post(
        "{AnUrl("refund/admin/ajax_refund_info")}",
        { id:id },
        function(data){
          ace.dialog({
            'title':'退货详细信息',
            'content':data,
            'width':1000,
            'cancel':function(){
              $('.aceDialog').hide();
            }
          })
        }
    )
  });

  $('.cancelRefund').click(function(){
    var id = $(this).closest('tr').data('id');
    var url = siteUrl+'/refund/admin/cancel_refund';
    showConfirm('您确定要取消当前退款吗？', 1, function(){
      $.post(url, { id:id }, function(json){
        if (json.info == 'ok') {
          showMsg('取消成功');
          setTimeout(function(){
            location.href = location.href;
          }, 500);
        } else {
          showMsg(json.info);
        }
      }, 'json');
    });
  });

  // 编辑
  $('body').on('click', '.js_editRefundRelation', function(){
    var type = $(this).data('type');
    var that = $(this);
    var relationId = $(this).closest('tr').data('relation_id');
    var refundNum   = $(this).parent().siblings('.js_refundNum');
    var currNum     = parseInt(refundNum.data('refund_num'));
    var currPrice   = parseFloat(refundNum.data('refund_price'));
    var maxNum      = parseInt(refundNum.data('max_num'));
    var url         = siteUrl+'/refund/admin/edit_refund_relation';
    var isModify = $('.js_realTotalPrice').data('is_modify');
    if (type == 'edit') {
      refundNum.html('可退数量: '+maxNum+'<br/><input type="number" value="'+currNum+'">');
      $(this).html('保存');
      $(this).data('type', 'save');
    } else {
      currNum     = refundNum.children('input').val();
      if (currNum == 0 || isNaN(currNum)) currNum = 1;
      if (currNum > maxNum) currNum = maxNum;
      $.post(url, { relation_id:relationId, refund_num:currNum }, function(json){
        if (json.info == 'ok') {
          $('.js_refundTotalPrice').html(json.count);
          refundNum.html(currNum);
          refundNum.data('refund_num', currNum);
          refundNum.next().html(currPrice*currNum);
          that.html('编辑');
          that.data('type', 'edit');
          if (isModify != 1) {
            $('.js_refundTotalPrice_'+json.id).html(json.count);
            $('.js_realTotalPrice').val(json.count);
          }
        } else {
          showMsg(json.data);
        }
      }, 'json');
    }
  });

  // 修改实际退款金额
  $('body').on('click', '.js_editRealPrice', function(){
    var that = $(this);
    var price = $(this).prev().val();
    var refundId = $(this).data('id');
    var url   = siteUrl+'/refund/admin/edit_real_price';
    if (price < 0) {
      showMsg('请填写实际退款金额');
      return;
    }

    $.post(url, { refund_id:refundId,refund_price:price }, function(json){
      if (json.info == 'ok') {
        $('.js_refundTotalPrice_'+refundId).html(json.price);
        that.prev().val(json.price);
        that.prev().data('is_modify', 1);
        showMsg('实际退款金额修改成功，退款是将以此金额为准');
      } else {
        showMsg(json.info);
      }
    }, 'json');
  })

  // 删除
  $('body').on('click', '.js_deleteRefundRelation', function(){
    var relationId = $(this).closest('tr').data('relation_id');
    var url        = siteUrl+'/refund/admin/delete_refund_relation';
    var that       = $(this);
    var type       = $(this).data('type');
    var isModify = $('.js_realTotalPrice').data('is_modify');
    if (type == 'delete') {
      if (confirm('您确定要删除当前商品？')) {
        $.post(url, { relation_id:relationId, status:0 }, function(json){
          if (json.info == 'ok') {
            that.data('type', 'refresh');
            that.prev().remove();
            that.removeClass('btn-danger').addClass('btn-primary').html('恢复');
            that.parent().prev().children().removeClass('label-primary').addClass('label-default').html('失效');
            $('.js_refundTotalPrice').html(json.count);
            if (isModify != 1) {
              $('.js_refundTotalPrice_'+json.id).html(json.count);
              $('.js_realTotalPrice').val(json.count);
            }
          } else {
            showMsg(json.data);
          }
        }, 'json');
      }
    } else {
      $.post(url, { relation_id:relationId, status:1 }, function(json){
        if (json.info == 'ok') {
          that.data('type', 'delete');
          that.parent().prepend('<span class="btn btn-xs btn-primary js_editRefundRelation" data-type="edit">修改</span>');
          that.removeClass('btn-primary').addClass('btn-danger').html('删除');
          that.parent().prev().children().removeClass('label-default').addClass('label-primary').html('有效');
          $('.js_refundTotalPrice').html(json.count);
          if (isModify != 1) {
            $('.js_refundTotalPrice_'+json.id).html(json.count);
            $('.js_realTotalPrice').val(json.count);
          }
        } else {
          showMsg(json.data);
        }
      }, 'json');
    }
  });

  // 批量退款
  $('.js_processRefund').on('click', function(e){
    e.preventDefault();
    var href = $(this).attr('href');
    var ids = getIds($(this));
    if (ids.length < 1) {
      showMsg('请选择需要退款的订单');
      return;
    }

    $.post( href, { ids:ids.join(',') }, function(data){
        ace.dialog({
          'title':'退货详细信息',
          'content':data,
          'okValue':'确定批量退款',
          'cancelValue':'关闭',
          'width':800,
          'ok':function(){
            refunding(ids);
            return false;
          },
          'cancel':function(){
            $('.aceDialog').hide();
          }
        });
      }
    );
  });

  /*
  $('.js_refundPayPrice').on('click', function(){
    var id = $(this).closest('tr').data('id');
    var type = $(this).closest('tr').data('type');
    var url = siteUrl+'/refund/admin/ajax_request_refund';
    if (type == 1) {
      window.open(siteUrl+'/openapi/alipay/refund?refund_id='+id);
      showConfirm('当前退款需要到支付宝确认退款, 确认已完成退款操作？', 1,function(){
        location.href = location.href;
      }, function(){
        location.href = location.href;
      });
    } else {
      $.post(url, { id:id }, function(json){
        if (json.info == 'ok') {
          showMsg('退款提交成功');
          setTimeout(function(){
            location.href = location.href;
          }, 1000);
        } else {
          showMsg(json.info);
        }
      }, 'json');
    }
  });*/
  
  $('.refundOk').click(function(){
    if(!confirm('确定要执行此操作吗?')){ 
      return false;
    } 
    var id = $(this).closest('tr').data('id');
    window.location.href="{AnUrl('refund/admin/change_refund_status?id="+id+"&refund_status=5')}";
  })
  
  $('.refundCancel').click(function(){
    var id = $(this).closest('tr').data('id');
    ace.dialog({
      'title':'请填写驳回理由',
      'content':'<textarea style="margin:30px;width:550px;height:110px;" class="note"></textarea>',
      'ok':function(){
        var note = $('.note').val();
        if (!note) {
          alert('理由不能为空');
          return false;
        }
        window.location.href="{AnUrl('refund/admin/change_refund_status?id="+id+"&refund_status=30&note="+note+"')}";
      }
    })
  });
  // 显示退货的详细信息
  $('.js_refundPayPrice').on('click', function(){
    var id = $(this).closest('tr').data('id');
    var _this = $(this);
    var btnType = $(this).data('type');
    if (btnType == 'refund') {
      var title = '退款确认';
    } else {
      var title = '申请通过';
    }
    $.post(
      "{AnUrl("refund/admin/get_refund_before_info")}",
      { id:id },
      function(data){
        ace.dialog({
          'title':title,
          'content':data,
          'width':1000,
          'cancel':function(){
            $('.aceDialog').hide();
          },
          'ok' : function(){
            //$('.aceDialog').hide();
            var id   = _this.closest('tr').data('id');
            var type = _this.closest('tr').data('type');
            var url  = siteUrl+'/refund/admin/ajax_request_refund';
            var refundType = $('.js_refundType').val();
            var snCode     = getSnCode();
            var invoiceNo  = $('.js_invoiceNo').val();
            var invoiceVal = $('.js_invoiceNo').data('value');
            var invoiceType = $('.js_invoiceType').val();
            var invoiceCode = $('.js_invoiceCode').val();
            var invoiceCodeVal = $('.js_invoiceCode').data('value');

            if ((invoiceVal || invoiceCodeVal) && !invoiceNo) {
              showMsg('订单已打发票必须填写发票号');
              return false;
            }
            if ((invoiceVal || invoiceCodeVal) && !invoiceCode) {
              showMsg('订单已打发票必须填写发票代码');
              return false;
            }
            if ((invoiceNo && !invoiceCode) || (!invoiceNo && invoiceCode)) {
              showMsg('发票代码和发票编号必须同时存在');
              return false;
            }
            var haveSnCode = 0;
            $('.js_snCode').each(function(){
              if ($(this).val()) {
                haveSnCode = 1;
                return false;
              }
            });
            if (invoiceCode || invoiceNo || haveSnCode == 1) {
              var hasSn = 0;
              $('.js_snCode').each(function(){
                if (!$(this).val()) {
                  hasSn = 1;
                  return false;
                }
              });
              if (hasSn == 1) {
                showMsg('SN编号可能出现重复或有的未填写');
                return false;
              }
              if(invoiceType < 1) {
                if (!invoiceNo || !invoiceCode) {
                  showMsg('发票代码和发票编号必须填写');
                  return false;
                }
              }
            } else {
              snCode = '';
              invoiceNo = '';
              invoiceCode = '';
            }
            if (refundType == 0) {
              showMsg('请选择退款类型');
              return false;
            }

            // 更新退款类型
            var refundUrl = siteUrl+'/refund/admin/update_refund_type';
            $.post(refundUrl, { id:id, refund_type:refundType, sn_code:snCode, invoice_no:invoiceNo, invoice_code:invoiceCode }, function(){ });

            if (btnType == 'agree') {
              location.href = siteUrl+'/refund/admin';
              //window.location.href="{AnUrl('refund/admin/change_refund_status?id="+id+"&refund_status=5')}";
              return false;
            }
            if (type == 1) {
              window.open(siteUrl+'/openapi/alipay/refund?refund_id='+id);
              showConfirm('当前退款需要到支付宝确认退款, 确认已完成退款操作？', 1,function(){
                location.href = location.href;
              }, function(){
                location.href = location.href;
              });
            } else {
              $.post(url, { id:id }, function(json){
                if (json.info == 'ok') {
                  showMsg('退款提交成功');
                  setTimeout(function(){
                    location.href = location.href;
                  }, 1000);
                } else {
                  showMsg(json.info);
                  return;
                }
              }, 'json');
            }
          }
        })
      }
    )
  });
});


function getSnCode()
{
  var ids = new Array();
  var snS = new Array();
  $('.js_orderRelationId').each(function(){
    var sn = new Array();
    var id = $(this).data('order_relation_id');
    if (id) {
      $(this).find('.js_snCode').each(function(){
        var snCode = $(this).val();
        if (snCode) {
          if (in_array(snCode, snS)) {
            $(this).val('');
          } else {
            sn.push(snCode);
          }
          snS.push(snCode);
        }
      });
      ids.push(id+':'+sn.join(','));
    }
  });

  return ids.join('#');
}

// 判断某数是否在数组中
function in_array(search,array) {
    for(var i in array){
        if(array[i]==search){
            return true;
        }
    }
    return false;
}

function refunding(ids)
{
  var url = siteUrl+'/refund/admin/ajax_request_refund';
  var refundIds = ids;
  if (refundIds.length < 1) {
    return;
  }


  var fail = 0;
  for (var i = 0; i < refundIds.length; i++) {
    if (fail == 1) {
      showMsg('批量退款失败');
      return;
    }
    var tr = $('.js_refundTr'+refundIds[i]);
    var id = refundIds[i];
    console.log(id);
    tr.find('span').removeClass('label-warning').addClass('label-info').html('处理中...');
    setTimeout(function(){
      $.ajax({
        url:url,
        async:false,
        data: { id:id },
        dataType:'json',
        success:function(json){
          if (json.info == 'ok') {
            tr.find('span').removeClass('label-info').addClass('label-default').html('已提交');
          } else {
            fail = 1;
          }
        },
        error:function(){
          fail = 1;
        }
      });
    }, 1000);
  }
}

function getIds(obj)
{
  var ids = new Array();
  obj.closest('table').find('.listSelect').each(function(){
    var id = $(this).closest('tr').data('id');
    if ($(this).attr('checked') == 'checked') {
      ids.push(id);
    }
  });

  return ids;
}
</script>
{include_core file="admin/lib/footer.html"}